package com.alibaba.dingtalk.openapi.newmessage.helper;/*/*/

import com.alibaba.dingtalk.openapi.exception.ApiRuleException;
import com.alibaba.dingtalk.openapi.exception.OApiException;
import com.alibaba.dingtalk.openapi.exception.OApiResultException;
import com.alibaba.dingtalk.openapi.helper.Env;
import com.alibaba.dingtalk.openapi.newmessage.delivery.SendToConversationMsgDelivery;
import com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * 发送普通消息
 * @author 魏荣杰
 * @date 2019/5/20 15:11
 * @since v1.0
 * @version v1.0
 */
public class SendToConversationHelper {
    private static final Logger LOG = LoggerFactory.getLogger(SendToConversationHelper.class);

    /**
     * 接收者可以是单聊接收者或者群聊会话里的接收者，如果接收者是当前接口调用所使用的企业的员工，则是有效接收者。
     *
     * 接口返回所有有效接收者的userId。
     *
     * 非有效接收者是收不到消息的。
     */
    @Setter
    @Getter
    @ToString
    public static class SendToConversationResponse {
        Long errcode;
        String errmsg;
        String receiver;
    }


    /**
     * Description: 发送普通消息
     * @param accessToken
     * @param sendToConversationMsgDelivery
     * @return com.alibaba.dingtalk.openapi.newmessage.helper.SendToConversationHelper.SendToConversationResponse
     * @throws OApiException OApiException
     * @author 魏荣杰
     * @date 2019/5/20 15:26
     * @since v1.0
     */
    public static SendToConversationResponse send(String accessToken, SendToConversationMsgDelivery sendToConversationMsgDelivery) throws OApiException {
        String url = Env.OAPI_HOST + "/message/send_to_conversation?access_token=" + accessToken;
        JSONObject response;
        try {
            sendToConversationMsgDelivery.check();
            response = HttpHelper.httpPost(url, sendToConversationMsgDelivery.toJsonObject());
        } catch (ApiRuleException e) {
            LOG.error("Request /message/send_to_conversation param error", e);
            throw new OApiResultException("Request /message/send_to_conversation param check error!");
        } catch (OApiException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("Access /message/send_to_conversation error", e);
            throw new OApiResultException("Access /message/send_to_conversation error!");
        }
        SendToConversationResponse sendToConversationResponse = null;
        if (Objects.nonNull(response)) {
            sendToConversationResponse = JSONObject.parseObject(response.toJSONString(), SendToConversationResponse.class);
        }

        return sendToConversationResponse;
    }
}
